#!/bin/bash

patch_rancher_monitoring_chart()
{
  local chart_dir=$1 #${CHARTS_DIR}
  local monitoring_version=$2 #MONITORING_VERSION
  local pkg_monitoring_path=$3 #${PKG_PATCH_MONITORING_PATH}
  local cwd=$(pwd)

  if [ ! -d "${pkg_monitoring_path}/${monitoring_version}" ]; then
    echo "NOTE: there is no related path: ${pkg_monitoring_path}/${monitoring_version} to patch, SKIP"
    return 0
  fi

  cd ${chart_dir}
  tar zxf rancher-monitoring-${monitoring_version}.tgz --warning=no-timestamp

  local origfile="./rancher-monitoring/charts/grafana/templates/nginx-config.yaml"
  local newfile="${pkg_monitoring_path}/${monitoring_version}/nginx-config.yaml"
  echo "patch original file $origfile"
  if [ -f "$origfile" ]; then
    ls -alth "$origfile"
    echo "diff"
    # when files are different, `diff` will return 1
    diff "$origfile" "$newfile" || true
    rm -f "$origfile"
  else
    echo "original file $origfile is not found"
  fi

  # replace with new file
  cp -f "$newfile" "$origfile"
  echo "patched file"
  ls -alth "$origfile"

  # replace shell image version; yq can also work, but it strips all blank lines; use patch instead
  local valuesfile="./rancher-monitoring/values.yaml"
  local difffile="${pkg_monitoring_path}/${monitoring_version}/patch-values-shell-version.diff"
  echo "patch rancher/shell image version"
  echo "the current values.yaml has following shell image version"
  grep "rancher/shell" $valuesfile -1 || true
  if [ -f "$difffile" ]; then
    patch $valuesfile $difffile
  else
    echo "diff file $difffile is not found"
  fi
  echo "the patched values.yaml has following shell image version"
  grep "rancher/shell" $valuesfile -1 || true

  # remove existing chart
  rm -f ${chart_dir}/rancher-monitoring-${monitoring_version}.tgz

  # helm pack new
  helm package rancher-monitoring
  rm -rf rancher-monitoring
  echo "finish patch ranch-monitoring chart"
  cd $cwd
}

